package com.buildings.util;

import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.buildings.activity.TownHouseFormActivity;
import com.buildings.adapter.PhotoRecycleAdapter;
import com.buildings.api.Api;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PhotoRecycleBuild {
    private Activity activity;
    private RecyclerView recyclerView;
    List<Uri> srcList = new ArrayList<>();

    List<String> srcHttpList = new ArrayList<>();
    private PhotoRecycleAdapter photoRecycleAdapter;
    private int joninType;


    public List<Uri> getSrcList() {
        return srcList;
    }

    public void setSrcList(List<Uri> srcList) {
        this.srcList = srcList;
    }

    public PhotoRecycleBuild(Activity activity, RecyclerView recyclerView) {
        this.activity = activity;
        this.recyclerView = recyclerView;
        initRecycleManager();
        initRecycleAdapter();
    }

    public void setHttpUrl(String httpUrl){
        if (TextUtils.isEmpty(httpUrl)){
            return;
        }
        srcHttpList.clear();
        srcList.clear();
        String[] httpUrlArr = httpUrl.split(",");
        for (int i = 0;i<httpUrlArr.length;i++){
            srcHttpList.add(httpUrlArr[i]);
            srcList.add(Uri.parse(""));
        }
        photoRecycleAdapter.notifyDataSetChanged();
    }

    public PhotoRecycleBuild(Activity activity, RecyclerView recyclerView, int joninType) {
        this.activity = activity;
        this.recyclerView = recyclerView;
        this.joninType = joninType;
        initRecycleManager();
        initRecycleAdapter();
    }

    private void initRecycleManager() {
        GridLayoutManager layoutManager = new GridLayoutManager(activity, 4);
        recyclerView.setLayoutManager(layoutManager);
    }

    private void initRecycleAdapter() {
        photoRecycleAdapter = new PhotoRecycleAdapter(activity, srcList, srcHttpList,joninType
                , new PhotoRecycleAdapter.OnItemClickListener() {
            @Override
            public void onQuery(View view, int position) {
            }

            @Override
            public void onDelete(View view, int position) {
                srcList.remove(position);
                photoRecycleAdapter.notifyDataSetChanged();
            }

            @Override
            public void onAddView(View view, int position) {
                HYDialogUtils.showImagePickDialog(activity, 10 - srcList.size());
            }
        });
        recyclerView.setAdapter(photoRecycleAdapter);
    }

    public void updataAdapter(List<Uri> list_1) {
        srcList.addAll(list_1);
        for (Uri uri : list_1) {
            String path = ImageUtils.getImageAbsolutePath19(activity, uri);
        }
        photoRecycleAdapter.update(srcList);
    }

    public void submitImage(List<Uri> srcList,int type, ImageCallBack imageCallBack) {
        this.imageCallBack = imageCallBack;
        if (srcList.size() == 0){
            this.imageCallBack.onCallBack("");
            return;
        }
        uploadImage(type,srcList);
    }

    public interface ImageCallBack {
        void onCallBack(String url);
    }

    private ImageCallBack imageCallBack;

    public void uploadImage(int type,List<Uri> list) {
        MultipartBody.Builder mbody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (int i = 0; i < list.size(); i++) {
            try {
                RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"),FileUtil.uriToFile(list.get(i),activity));
                String filename = "img_" + System.currentTimeMillis() + ".jpg";
                MultipartBody.Part body = MultipartBody.Part.createFormData("multipartFiles", filename, requestBody);
                mbody.addFormDataPart("multipartFiles", filename, requestBody);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        mbody.addFormDataPart("type", type+"");
        mbody.setType(MultipartBody.FORM);
        RequestBody requestBody = mbody.build();
        final Request request = new Request.Builder()
                .url(Api.UPLOADIMAGES)
                .post(requestBody)
                .build();

        OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
        httpBuilder.readTimeout(20000, TimeUnit.SECONDS)
                .connectTimeout(20000, TimeUnit.SECONDS)
                .writeTimeout(20000, TimeUnit.SECONDS)
        ;
        OkHttpClient okHttpClient = httpBuilder.build();
        okHttpClient.newCall(request).
                enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }

                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {
                        if (response.isSuccessful()) {
                            String result = response.body().string();
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                int code = jsonObject.getInt("code");
                                if(code == 200){
                                    String imageUrl = jsonObject.getString("data");
                                    imageCallBack.onCallBack(imageUrl);
                                }else {
                                    CustomToast.showToast(activity,"图片上传失败");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                CustomToast.showToast(activity,"图片上传失败");

                            }

                            if (response.body() != null) {
                                response.body().close();
                            }
                        }
                    }
                });
    }
}
